<template>
  <div v-loading="loading" class="range-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
        <!-- 新增按钮 -->
        <el-button type="primary" @click="showAddDialog">新增</el-button>
        </el-form-item>
        <el-form-item label="靶场名称">
          <el-input v-model="searchForm.rangeName" placeholder="请输入靶场名称" clearable />
        </el-form-item>
        <el-form-item label="靶场类型">
          <el-input v-model="searchForm.rangeType" placeholder="请输入靶场类型" clearable />
        </el-form-item>
        <el-form-item label="难易度">
          <el-select
              v-model="searchForm.difficultyId"
              placeholder="请选择难易度"
              clearable
              class="difficulty-select"
          >
            <el-option
                v-for="level in difficultyLevels"
                :key="level.difficultyId"
                :label="level.rangeDifficulty"
                :value="level.difficultyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 靶场卡片列表 -->
    <el-row :gutter="20" class="card-row">
      <el-col v-for="(item, index) in rangeList" :key="item.rangeId" :span="6" class="card-col">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>{{ item.rangeName }}</span>
              <div v-if="!item.isEditing">
                <el-button @click="editItem(item)">编辑</el-button>
                <!-- 添加删除按钮 -->
                <el-button type="danger" @click="deleteItem(item)">删除</el-button>
              </div>
              <div v-else class="edit-buttons">
                <el-button @click="cancelEdit(item)" >取消</el-button>
                <el-button type="primary" @click="saveEdit(item)" >确定</el-button>
              </div>
            </div>
          </template>
          <el-form label-position="left" label-width="75px" class="item-form">
            <el-form-item label="靶场类型:">
              <span v-if="!item.isEditing">{{ item.rangeType || 'N/A' }}</span>
              <el-input
                  v-else
                  v-model="item.rangeType"
                  placeholder="请输入靶场类型"
              ></el-input>
            </el-form-item>
            <el-form-item label="难易度:">
              <span v-if="!item.isEditing">{{ getDifficultyName(item.difficultyId) }}</span>
              <el-select v-else v-model="item.difficultyId" placeholder="请选择难易度">
                <el-option
                    v-for="level in difficultyLevels"
                    :key="level.difficultyId"
                    :label="level.rangeDifficulty"
                    :value="level.difficultyId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="端口号:">
              <span v-if="!item.isEditing">{{ item.exposePort || 'N/A' }}</span>
              <el-input v-else v-model="item.exposePort" placeholder="请输入端口号"></el-input>
            </el-form-item>
            <el-form-item label="存储路径:">
              <div v-if="!item.isEditing">
               <span v-if="item.minioUrl" class="ellipsis" @click="showMinioUrl(item)">
               {{ item.minioUrl.length > 20 ? item.minioUrl.substring(0, 20) + '...' : item.minioUrl }}
              </span>
                <span v-else>N/A</span>
              </div>
              <el-input v-else v-model="item.minioUrl" placeholder="请输入 MinIO URL"></el-input>
            </el-form-item>
            <el-form-item label="描述:">
              <span v-if="!item.isEditing">{{ item.rangeDesc }}</span>
              <el-input v-else v-model="item.rangeDesc" type="textarea" placeholder="请输入描述"></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增表单弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增靶场" width="50%">
      <el-form :model="addForm" label-width="120px">
        <el-form-item label="上传镜像">
          <el-upload
              action="#"
              :on-change="handleFileChange"
              :auto-upload="false"
              :file-list="fileList"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="靶场名称">
          <el-input v-model="addForm.targetRangeName" placeholder="请输入靶场名称"></el-input>
        </el-form-item>
        <el-form-item label="靶场类型">
          <el-input v-model="addForm.targetRangeType" placeholder="请输入靶场类型"></el-input>
        </el-form-item>
        <el-form-item label="难易度">
          <el-select v-model="addForm.difficultyId" placeholder="请选择难易度">
            <el-option
                v-for="level in difficultyLevels"
                :key="level.difficultyId"
                :label="level.rangeDifficulty"
                :value="level.difficultyId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description" type="textarea" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="端口号">
          <el-input v-model="addForm.exposePort" placeholder="请输入端口号"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="addForm.rangeTag" placeholder="请输入标签"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import rangeMange from '@/api/Backend/rangeMange';
import { ElMessage } from 'element-plus';

interface RangeItem {
  rangeId: string;
  rangeName: string;
  rangeType: string;
  difficultyId: number;
  exposePort: string | null;
  minioUrl: string | null;
  rangeDesc: string;
  isEditing: boolean;
}

interface DifficultyLevel {
  difficultyId: number;
  rangeDifficulty: string;
}

interface SearchForm {
  rangeName?: string;
  rangeType?: string;
  difficultyId?: number;
  pageNum?: number;
  pageSize?: number;
}

const rangeList = ref<RangeItem[]>([]);
const difficultyLevels = ref<DifficultyLevel[]>([]);
const loading = ref<boolean>(false);
const searchForm = reactive<SearchForm>({
  rangeName: '',
  rangeType: '',
  difficultyId: undefined,
  pageNum: 1,
  pageSize: 10
});

const showMinioUrl = (item: RangeItem) => {
  ElMessageBox.prompt('存储路径', '完整路径', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: item.minioUrl // 设置初始值为当前的 minioUrl
  }).then(({ value }) => {
    // 用户点击确定后的操作，这里可以添加保存逻辑
    console.log('输入的值:', value);
  }).catch(() => {
    // 用户取消操作
  });
};


// 获取难易度名称
const getDifficultyName = (difficultyId: number) => {
  const level = difficultyLevels.value.find(l => l.difficultyId === difficultyId);
  return level ? level.rangeDifficulty : `Level${difficultyId}`;
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 先获取难易度列表
    const levelResponse = await rangeMange.queryLevelList();
    if (levelResponse.code === 200) {
      difficultyLevels.value = levelResponse.data;
    }

    // 获取靶场列表
    const response = await rangeMange.listPage(searchForm);
    if (response.code === 200) {
      rangeList.value = response.data.list.map(item => ({
        ...item,
        isEditing: false
      }));
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1; // 重置页码
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.rangeName = '';
  searchForm.rangeType = '';
  searchForm.difficultyId = undefined;
  handleSearch();
};

onMounted(() => {
  loadData();
});

const editItem = (item: RangeItem) => {
  item.isEditing = true;
};

const cancelEdit = (item: RangeItem) => {
  item.isEditing = false;
};

const saveEdit = async (item: RangeItem) => {
  try {
    const updateData = {
      rangeId: item.rangeId,
      rangeName: item.rangeName,
      rangeType: item.rangeType,
      difficultyId: item.difficultyId,
      exposePort: item.exposePort,
      minioUrl: item.minioUrl,
      rangeDesc: item.rangeDesc
    };

    const response = await rangeMange.update(updateData);

    if (response.code === 200) {
      item.isEditing = false;
      ElMessage.success('修改信息成功');
    } else {
      ElMessage.error(response.msg || '修改信息失败');
    }
  } catch (error) {
    console.error('Failed to save edit:', error);
    ElMessage.error('修改信息时发生错误');
  }
};

// 新增表单相关
const addDialogVisible = ref(false);
const addForm = reactive({
  targetRangeFile: null,
  targetRangeName: '',
  targetRangeType: '',
  difficultyId: undefined,
  description: '',
  exposePort: '',
  rangeTag: ''
});
const fileList = ref([]);

const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleFileChange = (file) => {
  addForm.targetRangeFile = file.raw;
  fileList.value = [file];
};
const deleteItem = async (item: RangeItem) => {
  try {
    // 确认是否要删除
    const confirmResult = await ElMessageBox.confirm(
        '此操作将永久删除该靶场, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    if (confirmResult === 'confirm') {
      // 调用删除接口
      const response = await rangeMange.delete({ rangeId: item.rangeId });

      if (response.code === 200) {
        ElMessage.success('删除成功');
        // 重新加载数据
        loadData();
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete:', error);
      ElMessage.error('删除时发生错误');
    }
  }
};
1
const submitAddForm = async () => {
  // 构建 FormData 对象
  const formData = new FormData();
  formData.append('targetRangeFile', addForm.targetRangeFile);
  formData.append('targetRangeName', addForm.targetRangeName);
  formData.append('targetRangeType', addForm.targetRangeType);
  formData.append('difficultyId', addForm.difficultyId.toString());
  formData.append('description', addForm.description);
  formData.append('exposePort', addForm.exposePort);
  formData.append('rangeTag', addForm.rangeTag);

  try {
    const response = await rangeMange.upload(formData);
    if (response.data.code === 200) {
      ElMessage.success('新增成功');
      addDialogVisible.value = false;
      // 重新加载数据
      loadData();
    } else {
      ElMessage.error(response.data.msg || '新增失败');
    }
  } catch (error) {
    console.error('Failed to add:', error);
    ElMessage.error('新增时发生错误');
  }
};
</script>

<style scoped>
.range-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

/* 新增样式 - 调整难易度下拉框宽度 */
.search-form :deep(.difficulty-select) {
  width: 200px; /* 可以调整这个值来改变宽度 */
}

/* 或者更精确地选择难易度下拉框 */
.search-form :deep(.el-form-item:nth-child(3) .el-select) {
  width: 200px;
}

.card-row {
  margin-bottom: 20px;
}

.card-col {
  margin-bottom: 20px;
}

.box-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  height: 360px;
  display: flex;
  flex-direction: column;
}

.box-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.item-form {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
  flex: 1;
  overflow-y: auto;
  padding: 0 10px;
}

.item-form .el-form-item {
  margin-bottom: 8px;
}

.edit-buttons {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-col {
    width: 100%;
  }
}
</style>
